from django.shortcuts import render, get_object_or_404, redirect
from .models import Notice

from django.utils import timezone
from .forms import NoticeForm
from .models import BlackLetter
from django.http import JsonResponse
from .models import PrivateLetter
from django.views.decorators.csrf import csrf_exempt


# Create your views here.
# 列表视图：展示所有通知
def notice_list(request):
    notices = Notice.objects.all().order_by('-create_time')
    return render(request, 'notice_list.html', {'notices': notices})


# 详情视图：查看单个通知的详细信息
def notice_detail(request, pk):
    notice = get_object_or_404(Notice, pk=pk)
    return render(request, 'notice_detail.html', {'notice': notice})


# 创建或更新通知视图：如果 pk 存在，则更新，否则创建
def notice_update(request, pk=None):
    if pk:
        notice = get_object_or_404(Notice, pk=pk)
    else:
        notice = None

    if request.method == 'POST':
        form = NoticeForm(request.POST, instance=notice)
        if form.is_valid():
            notice = form.save(commit=False)
            notice.create_time = timezone.now()  # 更新创建时间
            notice.save()
            return redirect('notice_detail', pk=notice.pk)
    else:
        form = NoticeForm(instance=notice)

    return render(request, 'notice_form.html', {'form': form})


# 删除通知
def notice_delete(request, pk):
    notice = get_object_or_404(Notice, pk=pk)
    notice.delete()
    return redirect('notice_list')


def send_private_letter(request):
    if request.method == 'POST':
        user_id = request.POST.get('user_id')
        receive_id = request.POST.get('receive_id')
        message = request.POST.get('message')

        # 创建新的私信记录
        PrivateLetter.objects.create(
            userId=user_id,
            receiveId=receive_id,
            message=message,
            issend=True
        )

        return JsonResponse({'status': 'success', 'message': '私信发送成功'})

    return JsonResponse({'status': 'error', 'message': '无效请求'})


@csrf_exempt
def get_private_letters(request):
    if request.method == 'GET':
        user_id = request.GET.get('user_id')

        # 获取指定用户的所有私信
        letters = PrivateLetter.objects.filter(receiveId=user_id)
        data = list(letters.values('userId', 'message', 'create_time'))

        return JsonResponse({'status': 'success', 'data': data})

    return JsonResponse({'status': 'error', 'message': '无效请求'})


# def black_list_view(request):
#     # 获取所有黑名单记录
#     black_list = BlackLetter.objects.all()
#     print(black_list)
#     context = {
#         'black_list': black_list
#     }
#     return render(request, 'black_list.html', context)


def xzbmessage(request):
    # 获取所有黑名单记录
    black_list = BlackLetter.objects.all()
    print(black_list)
    context = {
        'black_list': black_list
    }
    return render(request, "notice/message.html", context)


# def unblock_user(request, blackId):
#     # 获取所有的黑名单数据
#     # userid = request.session.get("userid")
#     black_list = BlackLetter.objects.filter(userId=1, blackId=blackId)
#     black_list.delete()
#     # return JsonResponse({'detail': 'success'})
#     return render(request, "notice/message.html", {'black_list': black_list})


def unblock_user(request, blackId):
    # 假设你已经确认用户 ID 是 1，实际情况中应该从 session 或其他身份验证机制获取
    userId = 1

    # 查找黑名单中的记录
    black_list = BlackLetter.objects.filter(userId=userId, blackId=blackId)
    print("type:", type(black_list))
    # 删除找到的记录
    black_list[0].delete()

    black_list = BlackLetter.objects.filter(userId=userId)

    # 渲染结果页面，传递删除后的黑名单（此处应为空，因为已删除）
    return render(request, "notice/message.html", {'black_list': black_list})


def xzbchat(request):
    return render(request, "notice/chat.html")


def xzbdetail(request):
    return render(request, "notice/detail.html")
